using System.Collections.Generic;
using System.Xml;
using mock_ehr_lib.Data.LookupServices;

namespace mock_ehr_lib.Model.Summary
{
    public class FamilyHistoryItem
    {
        public string Relation { get; set; }
        public string Assertion { get; set; }
        public static IEnumerable<FamilyHistoryItem> FromCCD(XmlDocument ccdXml, XmlNamespaceManager namespaceManager)
        {
            var familyHistoryItems = new List<FamilyHistoryItem>();
            const string familyHistoryXPath = "//ns:observation[ns:templateId[@root='2.16.840.1.113883.10.20.1.22']]";
            var familyHistoryNodes = ccdXml.SelectNodes(familyHistoryXPath, namespaceManager);
            if (familyHistoryNodes == null)
                return familyHistoryItems;
            var familyHistoryNodesEnumerator = familyHistoryNodes.GetEnumerator();
            if(familyHistoryNodesEnumerator == null)
                return familyHistoryItems;
            while (familyHistoryNodesEnumerator.MoveNext())
            {
                var current = familyHistoryNodesEnumerator.Current as XmlNode;
                var relationNode = current.SelectSingleNode("./ns:subject/ns:relatedSubject/ns:code/@displayName", namespaceManager);
                var relation = relationNode == null ? null : relationNode.Value;
                var assertionNode = current.SelectSingleNode("./ns:value", namespaceManager);
                string assertion = null;
                if (assertionNode != null)
                {
                    if (string.IsNullOrWhiteSpace(assertionNode.InnerText))
                    {
                        var codeSystem = assertionNode.Attributes["codeSystem"].Value;
                        var code = assertionNode.Attributes["code"].Value;
                        var lookupService = LookupServiceFactory.GetLookupServiceByCodeSystem(codeSystem);
                        assertion = lookupService.GetDescriptionByCode(code);
                    }
                    else
                    {
                        assertion = assertionNode.InnerText; // the condition or statement
                    }
                }
                var familyHistoryItem = new FamilyHistoryItem { Relation = relation, Assertion = assertion };
                familyHistoryItems.Add(familyHistoryItem);
            }
            return familyHistoryItems;
        }
    }
}